import { _decorator, animation, AnimationState, Component, Node, SkeletalAnimation, v3, Vec3 } from 'cc';
import { NPCController } from '../Controller/NPCController';
import { GameManager } from '../GameManager';
const { ccclass, property } = _decorator;

@ccclass('FatherController')
export class FatherController extends NPCController {
    public ani: SkeletalAnimation = null;
    private IsSaveplayer: boolean = false;//是否正在拯救孩子
    protected start(): void {
        super.start();
        this.ani = this.node.getChildByName("模型").getComponent(SkeletalAnimation);
        this.schedule(() => {
            if (GameManager.Instance.PlayerIsOndilemma) {
                GameManager.Instance.FatherFind();
            }
        }, 3)
        this.schedule(() => {
            if (GameManager.Instance.PlayerIsOndilemma) {
                if (this.node.getWorldPosition().subtract(GameManager.Instance.PlayerNode.getWorldPosition()).length() < 1.2) {
                    this.IsSaveplayer = true;
                    this.Path = [];
                    this.IsOnPathWalkMove = false;
                    this.scheduleOnce(() => {
                        GameManager.Instance.inOutdilemma(false);
                    }, 0.5)
                    this.scheduleOnce(() => {
                        this.IsSaveplayer = false;
                    }, 1.5)
                }
            }
        }, 0.6)
    }
    protected update(dt: number): void {
        if (this.IsOnPathWalkMove && this.Path.length > 0) {
            let _v2: Vec3 = v3(this.Path[0].x, this.Path[0].y, this.Path[0].z);
            let _v3 = _v2.subtract(this.node.position);
            this.node.forward = v3(_v3.x, 0, _v3.z);
            if (!this.IsSaveplayer) {
                this.node.setPosition(this.node.position.clone().add(v3(this.Speed * _v3.normalize().x * dt, this.Speed * _v3.normalize().y * dt, this.Speed * _v3.z * dt)));
            }

            if (this.GetTwoPosXZDis(this.node.position, this.Path[0]) < 0.02) {
                this.Path.splice(0, 1);
                if (this.Path.length == 0) {
                    this.IsOnPathWalkMove = false;
                }
            }
        }
        this.SetAnimation();

    }


    SetAnimation() {
        let stateName: string = "idel";
        if (this.IsOnPathWalkMove) {
            stateName = "running";
        }
        if (this.IsSaveplayer) {
            stateName = "take";
        }

        if (!this.ani.getState(stateName).isPlaying) {
            this.ani.play(stateName);
        }
    }
}


